package com.atf.atfconfigurator;

import java.util.LinkedHashMap;
import java.util.Properties;

import javax.servlet.annotation.WebServlet;

import org.apache.commons.configuration.Configuration;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.configuration.PropertiesConfiguration;
import org.atf.model.dao.PreferenceDAO;
import org.atf.model.entity.Preference;

import com.atf.atfconfigurator.views.ClusterView;
import com.atf.atfconfigurator.views.DSConnectionPoolView;
import com.atf.atfconfigurator.views.DataSourceView;
import com.atf.atfconfigurator.views.DeployInfoViews;
import com.atf.atfconfigurator.views.InfoViews;
import com.atf.atfconfigurator.views.J2CAlias;
import com.atf.atfconfigurator.views.JVMPropertiesView;
import com.atf.atfconfigurator.views.JdbcProviderView;
import com.atf.atfconfigurator.views.ListenPortView;
import com.atf.atfconfigurator.views.MQConnectionFactoryView;
import com.atf.atfconfigurator.views.MQConnectionPoolView;
import com.atf.atfconfigurator.views.MQQueueView;
import com.atf.atfconfigurator.views.SharedLibraryView;
import com.atf.atfconfigurator.views.ThreadPoolView;
import com.atf.atfconfigurator.views.VirtualHostView;
import com.atf.atfconfigurator.views.WebContainerView;
import com.atf.atfconfigurator.views.WebsphereVariablesView;
import com.vaadin.annotations.Theme;
import com.vaadin.annotations.VaadinServletConfiguration;
import com.vaadin.navigator.Navigator;
import com.vaadin.server.FontAwesome;
import com.vaadin.server.Page;
import com.vaadin.server.ThemeResource;
import com.vaadin.server.VaadinRequest;
import com.vaadin.server.VaadinServlet;
import com.vaadin.shared.ui.label.ContentMode;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComponentContainer;
import com.vaadin.ui.CssLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.MenuBar;
import com.vaadin.ui.MenuBar.MenuItem;
import com.vaadin.ui.Notification;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;

import java.util.Map.Entry;

@SuppressWarnings("serial")
@Theme("atfconfigurator")
public class AtfconfiguratorUI extends UI {
	CssLayout menu = new CssLayout();
	PreferenceDAO preferenceDAO= new PreferenceDAO();
	CssLayout menuItemsLayout = new CssLayout();
    {
        menu.setId("testMenu");
    }
	AtfMenuLayout root = new AtfMenuLayout();
	ComponentContainer viewDisplay = root.getContentContainer();
	public Navigator navigator;
	private PropertiesConfiguration wasConfigProperty;
	@WebServlet(value = "/", asyncSupported = true)
	@VaadinServletConfiguration(productionMode = false, ui = AtfconfiguratorUI.class)
	public static class Servlet extends VaadinServlet {
	}

	@Override
	protected void init(VaadinRequest request) {
		if (getPage().getWebBrowser().isIE()
                && getPage().getWebBrowser().getBrowserMajorVersion() == 9) {
            menu.setWidth("320px");
        }
		getPage().setTitle("ATF WAS Application Configurator");
		setContent(root);
		root.setWidth("100%");
		String fileName = request.getParameter("fileName");
		String tempDir="/tmp";
		Preference tempDirPref= preferenceDAO.getPreferenceByName("TEMP_DIR");
		if(tempDirPref != null){
			tempDir=tempDirPref.getpValue();
		}
		fileName=tempDir+"/"+fileName;
		String type= request.getParameter("type");
		if( type == null){
			type= "";
		}
		String profileName= request.getParameter("profileHostname");
		String port = request.getParameter("profileHost");
		if(fileName != null){
			
			wasConfigProperty =loadWasConfigurationFile(fileName);
			if( wasConfigProperty != null & type.equalsIgnoreCase("config")){
				root.addMenu(buildWasConfigMenu());
				navigator = new Navigator(this, viewDisplay);
				navigator.addView("Info", InfoViews.class);
				navigator.addView("JdbcProvider", JdbcProviderView.class);
				navigator.addView("Cluster", ClusterView.class);
				navigator.addView("JVMProperties", JVMPropertiesView.class);
				navigator.addView("WebContainer", WebContainerView.class);
				navigator.addView("ThreadPool", ThreadPoolView.class);
				navigator.addView("VirtualHost", VirtualHostView.class);
				navigator.addView("WebsphereVariables", WebsphereVariablesView.class);
				navigator.addView("SharedLibrary", SharedLibraryView.class);
				navigator.addView("J2CAlias", J2CAlias.class);
				navigator.addView("DataSource", DataSourceView.class);
				navigator.addView("DSConnectionPool", DSConnectionPoolView.class);
				navigator.addView("MQConnectionFactory", MQConnectionFactoryView.class);
				navigator.addView("MQQueue", MQQueueView.class);
				navigator.addView("ListenPort", ListenPortView.class);
				navigator.addView("MQConnectionPool", MQConnectionPoolView.class);
				
				final String f = Page.getCurrent().getUriFragment();
		        if (f == null || f.equals("")) {
		            navigator.navigateTo("Info");
		        }
		       
			}if(wasConfigProperty != null & type.equalsIgnoreCase("deploy")){
				root.addMenu(buildWasDeployMenu());
				navigator = new Navigator(this, viewDisplay);
				navigator.addView("Info", DeployInfoViews.class);
				final String f = Page.getCurrent().getUriFragment();
		        if (f == null || f.equals("")) {
		            navigator.navigateTo("Info");
		        }
			}
			else{
				viewDisplay.addComponent(new Label("Was Configuration Can't be loaded", ContentMode.HTML));
			}
			
		}else{
			viewDisplay.addComponent(new Label("Was Configuration File Not found", ContentMode.HTML));
		}
	}
	CssLayout buildWasDeployMenu() {
		 final HorizontalLayout top = new HorizontalLayout();
	     top.setWidth("100%");
	     top.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
	     top.addStyleName("valo-menu-title");
	     menu.addComponent(top);
	     final Label title = new Label(
	                "<h3> AFT Configurator</strong></h3>", ContentMode.HTML);
	        title.setSizeUndefined();
	        top.addComponent(title);
	        top.setExpandRatio(title, 1);
	     menuItemsLayout.setPrimaryStyleName("valo-menuitems");
	     menu.addComponent(menuItemsLayout);
	    
	     
	     //Save Button
	     final Button saveConf = new Button("Save", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 if(saveWasConfiguration()){
            		 Notification.show("SuccessFully Saved", Notification.Type.HUMANIZED_MESSAGE);
            	 }else{
            		 Notification.show("Error in Saving", Notification.Type.ERROR_MESSAGE);
            	 }
             }
         });
	     saveConf.setIcon(FontAwesome.SAVE);
	     saveConf.addStyleName("borderless-colored");
	    // saveConf.setPrimaryStyleName("valo-menu-item");
         menuItemsLayout.addComponent(saveConf);
         Label label = new Label("General", ContentMode.HTML);
         label.setPrimaryStyleName("valo-menu-subtitle");
         label.addStyleName("h4");
         label.setSizeUndefined();
         menuItemsLayout.addComponent(label);
	     final Button info = new Button("Info", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("Info");
             }
         });
	     info.setHtmlContentAllowed(true);
         info.setPrimaryStyleName("valo-menu-item");
         menuItemsLayout.addComponent(info);
         
	     return menu;
	     
	}
	
	 CssLayout buildWasConfigMenu() {
		 final HorizontalLayout top = new HorizontalLayout();
	     top.setWidth("100%");
	     top.setDefaultComponentAlignment(Alignment.MIDDLE_LEFT);
	     top.addStyleName("valo-menu-title");
	     menu.addComponent(top);
	     final Label title = new Label(
	                "<h3><strong>AFT Configurator</strong></h3>", ContentMode.HTML);
	        title.setSizeUndefined();
	        top.addComponent(title);
	        top.setExpandRatio(title, 1);
	     menuItemsLayout.setPrimaryStyleName("valo-menuitems");
	     menu.addComponent(menuItemsLayout);
	     
	     final Button saveConf = new Button("Save", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 if(saveWasConfiguration()){
            		 Notification.show("SuccessFully Saved", Notification.Type.HUMANIZED_MESSAGE);
            	 }else{
            		 Notification.show("Error in Saving", Notification.Type.ERROR_MESSAGE);
            	 }
             }
         });
	     saveConf.setIcon(FontAwesome.SAVE);
	     saveConf.addStyleName("borderless-colored");
	    // saveConf.setPrimaryStyleName("valo-menu-item");
         menuItemsLayout.addComponent(saveConf);
	     
	     Label label = new Label("General", ContentMode.HTML);
         label.setPrimaryStyleName("valo-menu-subtitle");
         label.addStyleName("h4");
         label.setSizeUndefined();
         menuItemsLayout.addComponent(label);
	     final Button info = new Button("Info", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("Info");
             }
         });
         
         info.setHtmlContentAllowed(true);
         info.setPrimaryStyleName("valo-menu-item");
         menuItemsLayout.addComponent(info);
         
         //Server Information Subsection
         label = new Label("Server Information", ContentMode.HTML);
         label.setPrimaryStyleName("valo-menu-subtitle");
         label.addStyleName("h4");
         label.setSizeUndefined();
         menuItemsLayout.addComponent(label);
         
         //cluster menu Button 
	     final Button cluster = new Button("Cluster", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("Cluster");
             }
         });
	     cluster.setHtmlContentAllowed(true);
	     cluster.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(cluster);
	     
	     //JVM Properties menu Button 	 
	     final Button jvmProps = new Button("JVM Properties", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("JVMProperties");
            	 
             }
         });
	     jvmProps.setHtmlContentAllowed(true);
	     jvmProps.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(jvmProps);
	     
	    //WebContainer menu Button 	 
	     final Button webcontainer = new Button("WebContainer", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("WebContainer");
            	 
             }
         });
	     webcontainer.setHtmlContentAllowed(true);
	     webcontainer.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(webcontainer );
	     
	     //ThreaPool menu Button 	 
	     final Button threadPool = new Button("ThreadPool", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("ThreadPool");
            	 
             }
         });
	     threadPool.setHtmlContentAllowed(true);
	     threadPool.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(threadPool );
	     
	     //Environment Subsection
	     
	     label = new Label("Environment", ContentMode.HTML);
         label.setPrimaryStyleName("valo-menu-subtitle");
         label.addStyleName("h4");
         label.setSizeUndefined();
         menuItemsLayout.addComponent(label);
         
         //VirtualHost Subsection
	     final Button vHost = new Button("Virtual Host", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("VirtualHost");
             }
         });
	     vHost.setHtmlContentAllowed(true);
	     vHost.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(vHost);
	     
	   //WebSphere Variable Subsection
	     final Button websphereVariables = new Button("WebSphere Variable", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("WebsphereVariables");
             }
         });
	     websphereVariables.setHtmlContentAllowed(true);
	     websphereVariables.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(websphereVariables);
	     
	   //VirtualHost Subsection
	     final Button sharedLibrary = new Button("Shared Library", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("SharedLibrary");
             }
         });
	     sharedLibrary.setHtmlContentAllowed(true);
	     sharedLibrary.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(sharedLibrary);
	     
	     
	     //Resource SubSection
	     label = new Label("Resources", ContentMode.HTML);
         label.setPrimaryStyleName("valo-menu-subtitle");
         label.addStyleName("h4");
         label.setSizeUndefined();
         menuItemsLayout.addComponent(label);
         
          //J2C Subsection
	      final Button j2cAlias = new Button("J2C Alias", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("J2CAlias");
             }
          });
	      j2cAlias.setHtmlContentAllowed(true);
	      j2cAlias.setPrimaryStyleName("valo-menu-item");
	      menuItemsLayout.addComponent(j2cAlias);
         
         //jdbcprovider Subsection
	     final Button jdbcprovider = new Button("JDBC Provider", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("JdbcProvider");
             }
         });
	     jdbcprovider.setHtmlContentAllowed(true);
	     jdbcprovider.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(jdbcprovider);
	     
	     //dataSource Subsection
	     final Button dataSource = new Button("DataSource", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("DataSource");
             }
         });
	     dataSource.setHtmlContentAllowed(true);
	     dataSource.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(dataSource);
	     
	     //Connection Pool Subsection
	     final Button dsConnectionPool = new Button("DS Connection Pool", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("DSConnectionPool");
             }
         });
	     dsConnectionPool.setHtmlContentAllowed(true);
	     dsConnectionPool.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(dsConnectionPool);
	     
         
         //MQ Connection Factories Subsection
	     final Button mqConnectionFactory = new Button("MQ Connection Factories", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("MQConnectionFactory");
             }
         });
	     mqConnectionFactory.setHtmlContentAllowed(true);
	     mqConnectionFactory.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(mqConnectionFactory);
	     
	    //MQ Queues Subsection
	     final Button mqQueue = new Button("MQ Queues", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("MQQueue");
             }
         });
	     mqQueue.setHtmlContentAllowed(true);
	     mqQueue.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(mqQueue);
	     
	     //Listen Ports Subsection
	     final Button listenPorts = new Button("Listen Ports", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("ListenPort");
             }
         });
	     listenPorts.setHtmlContentAllowed(true);
	     listenPorts.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(listenPorts);
	     
	     
	    // MQ Connection Pool Subsection
	     final Button mqConnectionPool = new Button("MQ Connection Pool", new ClickListener() {
             @Override
             public void buttonClick(final ClickEvent event) {
            	 navigator.navigateTo("MQConnectionPool");
             }
         });
	     mqConnectionPool.setHtmlContentAllowed(true);
	     mqConnectionPool.setPrimaryStyleName("valo-menu-item");
	     menuItemsLayout.addComponent(mqConnectionPool);
	     
	     
	     return menu;
	 }
	 
	 public PropertiesConfiguration loadWasConfigurationFile(String fileName){
		 try{
			 PropertiesConfiguration config = new PropertiesConfiguration();
			 config.setDelimiterParsingDisabled(true);
			 config.setFileName(fileName);
			 config.load();
			 return config;
		 }catch(Exception e){
			 System.err.println(e.getMessage());
		 }
		 return null;
	 }
	 
	 public PropertiesConfiguration getWasConfiguration(){
		 return this.wasConfigProperty;
	 }

	 public boolean saveWasConfiguration(){
		 try {
			this.wasConfigProperty.save();
			return true;
		} catch (ConfigurationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		 return false;
	 }

	public void updateCommitStatus() {
		// TODO Auto-generated method stub
		
	}

}